package cn.ccenjie.wsy.config.vcode;

import cn.ccenjie.wsy.config.SysConst;
import cn.ccenjie.wsy.utils.HttpUtils;
import cn.ccenjie.wsy.vo.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class VcodeAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        if(!"/login".equals(httpServletRequest.getRequestURI())) {
            // 非登录请求，放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        Object prical = HttpUtils.getParam("vcode", httpServletRequest);
        if(prical == null) {
            HttpUtils.wrire(httpServletResponse, Resp.fail("验证码不能为空"));
            return;
        }

        Object captchaId = HttpUtils.getParam("captchaId", httpServletRequest);
        if(captchaId == null) {
            HttpUtils.wrire(httpServletResponse, Resp.fail("验证码ID不能为空"));
            return;
        }

        Object serverCaptcha = redisTemplate.opsForValue().get(SysConst.CAPTCHA_PREFIX + captchaId);

        if(prical.equals(serverCaptcha)) {
            HttpUtils.wrire(httpServletResponse, Resp.fail("验证码不正确"));
            return;
        }

        // 验证通过，继续放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}


